package org.egedede.processmanager.ui;

import java.awt.GridBagLayout;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import org.egedede.commons.ui.FileChooser;
import org.egedede.commons.ui.GridBagLayoutBuilder;
import org.egedede.processmanager.ProcessDefinition;

public class ProcessDefinitionPanel extends JPanel {

	private static final long serialVersionUID = 3111843022424297251L;

	private final ResourceBundle bundle = ResourceBundle.getBundle("ui.ProcessDefinitionPanel");

	private final JTextField label = new JTextField();
	private final JTextField commandLine = new JTextField();
	private final FileChooser workingDir = new FileChooser();
	private final JTable env = new JTable();

	public ProcessDefinitionPanel() {
		super(new GridBagLayout());
		final GridBagLayoutBuilder b = new GridBagLayoutBuilder(this, bundle);
		int line = 0;
		b.addXYLabel("label", 0, line);
		b.addXY(label, 1, line);
		line++;

		b.addXYLabel("commandLine", 0, line);
		b.addXY(commandLine, 1, line);
		line++;

		b.addXYLabel("workingDir", 0, line);
		b.addXY(workingDir, 1, line);
		line++;

		b.addXYLabel("env", 0, line);
		line++;
		b.setWeight(1, 4);
		b.addXYWH(env, 0, line, 2, 1);
	}

	public void setProcessDefinition(final ProcessDefinition def) {
		label.setText(def.getLabel());
		commandLine.setText(def.getCommand());
		workingDir.setFile(def.getWorkingDir());
		this.updateEnv(def.getEnv());
	}

	public ProcessDefinition getProcessDefinition() {
		return new ProcessDefinition(label.getText(), commandLine.getText(), workingDir.getFile(), this.getEnv());
	}

	private Map<String, String> getEnv() {
		final Map<String, String> result = new HashMap<String, String>();
		final TableModel model = env.getModel();
		final int rowCount = model.getRowCount();
		for (int i = 0; i < rowCount; i++) {
			result.put((String) model.getValueAt(i, 0), (String) model.getValueAt(i, 1));
		}
		return result;
	}

	private void updateEnv(final Map<String, String> env2) {
		final DefaultTableModel model = (DefaultTableModel) env.getModel();
		final String[][] data = new String[env2.size()][2];
		int line = 0;
		for (final String key : env2.keySet()) {
			data[line][0] = key;
			data[line][1] = env2.get(key);
			line++;
		}
		final String[] labels = { "key", "value" };
		model.setDataVector(data, labels);

	}
}
